package com.wei.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wei.blog.common.constants.LikeConstatns;
import com.wei.service.ILikeService;
import com.wei.vo.LikeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.stereotype.Service;

@Service
public class ILikeServiceImpl implements ILikeService {

    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public void clickLike(LikeVo likeVo){
        //点赞 取消点赞
        redisTemplate.execute(new SessionCallback() {
            @Override
            public Object execute(RedisOperations operations) throws DataAccessException {
                String key = String.format(LikeConstatns.LIKE_TOPIC_KEY, likeVo.getEntityType(), likeVo.getEntityId());
                String userLikeKey = String.format(LikeConstatns.USER_LIKE_KEY, likeVo.getEntityUserId());

                //判断这个对象是否对这个对向点赞
                Boolean member = redisTemplate.opsForSet().isMember(key, likeVo.getUserId());
                //开启事务
                operations.multi();
                if (member) {
                    //如果用户已经点赞，则取消点赞
                    Long remove = redisTemplate.opsForSet().remove(key, likeVo.getUserId());
                    //被取消点赞的用户点赞数量减少
                    redisTemplate.opsForValue().decrement(userLikeKey);
                }else {
                    //如果用户未点赞，则增加点赞
                    Long add = redisTemplate.opsForSet().add(key, likeVo.getUserId());
                    //被点赞的用户点赞数量增加
                    redisTemplate.opsForValue().increment(userLikeKey);
                }

                //事务提交
                operations.exec();
                return null;
            }
        });
    }

    @Override
    public Long likeCount(LikeVo likeVo) {
        //统计（帖子或回复）点赞数量
        String key = String.format(LikeConstatns.LIKE_TOPIC_KEY, likeVo.getEntityType(), likeVo.getEntityId());
        return redisTemplate.opsForSet().size(key);
    }

    @Override
    public boolean likeStatus(LikeVo likeVo) {
        //判断被点赞的状态
        String key = String.format(LikeConstatns.LIKE_TOPIC_KEY, likeVo.getEntityType(), likeVo.getEntityId());
        return redisTemplate.opsForSet().isMember(key,likeVo.getUserId());
    }

    @Override
    public Long getUserLikeCount(Integer userId) {
        String userLikeKey = String.format(LikeConstatns.USER_LIKE_KEY, userId);
        Object o = redisTemplate.opsForValue().get(userLikeKey);
        if (o==null){
            //如果用户没被点过赞 返回0个赞
            return 0L;
        }
        return Long.parseLong(o.toString());
    }
}
